#!/bin/bash

# This script is the AppRun entry point used by an AppImage to set up the necessary environment
# and directory path for the application. It first ensures that the APPDIR variable is defined,
# representing the root of the AppImage filesystem. After setting up the environment, it delegates
# control to the `startapp.py` script, which is responsible for initiating the main Python
# application. This setup allows for a layered initialization process, ensuring that the
# application is launched with the correct context and dependencies within the AppImage's sandbox.
#
# AppRun Script Overview:
# -----------------------
#
# The AppRun script performs the following actions:
#
# 1. Sets the APPDIR environment variable if not already set, which specifies the AppImage's mount
#    point directory.
# 2. Exports additional environment variables required by the Python application.
# 3. Executes the Python interpreter bundled within the AppImage, passing along any arguments to
#    the startapp.py script, which in turn utilizes this module to launch the application.


# Check if APPDIR is already set, if not, determine and set it to the AppImage's mount directory.
# APPDIR needs to be set as it specifies the directory where the AppImage content is located.

set -e

if [ -n "$APPIMAGE" ]; then
    appimage_path=$(dirname "$APPIMAGE")
    if [ -d "$appimage_path/squashfs-root" ]; then
        export APPDIR="$appimage_path/squashfs-root"
    fi
fi

if [ -z $APPDIR ]; then
    export APPDIR=$(dirname $(readlink -f "$0"))
fi

# The script then delegates control to `startapp.py` by using the Python interpreter included within the AppImage.
# `startapp.py` is responsible for further initializing and starting the actual Python application.
# $@ passes all given arguments through to `startapp.py`.

exec $APPDIR/python/bin/python3 -P -m appimage --python-main ssh-mitm "$@"
